from detect import *
import time
import uiautomator2 as u2
import os
from adbutils import AdbDevice
import cv2
import subprocess
import checkimg
import pytesseract
import re
import shutil
import random
import Levenshtein

def Picture_Synthesis(son_img,serial,
                      coordinate=None):

    S_Img = Image.open(son_img)

    height,width = S_Img.size
    print('width=',width,'  height=',height)
    width = width+200
    height = height+200
    mother_img= np.ones((width, height, 3), dtype=np.uint8)

    mother_img[:, :, 0] = 255
    mother_img[:, :, 1] = 122
    mother_img[:, :, 2] = 0

    cv2.imwrite('D:\\image3\\wwwwwwwww.png', mother_img, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

    M_Img = Image.open('D:\\image3\\wwwwwwwww.png')

    factor = 1

    M_Img = M_Img.convert("RGBA")

    M_Img_w, M_Img_h = M_Img.size

    S_Img_w, S_Img_h = S_Img.size

    size_w = int(S_Img_w / factor)
    size_h = int(S_Img_h / factor)

    if S_Img_w > size_w:
        S_Img_w = size_w
    if S_Img_h > size_h:
        S_Img_h = size_h


    icon = S_Img.resize((S_Img_w, S_Img_h), Image.Resampling.LANCZOS)
    w = int((M_Img_w - S_Img_w) / 2)
    h = int((M_Img_h - S_Img_h) / 2)

    try:
        if coordinate==None or coordinate=="":
            coordinate=(w, h)
            M_Img.paste(icon, coordinate, mask=None)
        else:
            M_Img.paste(icon, coordinate, mask=None)
    except:
        print(" ")
    # 保存图片

    M_Img.save('D:\\image3\\'+serial+'-eeeeeeeeeeeeeeeeeeeee.png')

    return 'D:\\image3\\'+serial+'-eeeeeeeeeeeeeeeeeeeee.png'

def qqq(d,path,serial,rect):

    screenshot = d.screenshot(format='opencv')
    cv2.imwrite(path+serial+'-testscreenshotold.png', screenshot, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])
    x,y,w,h=DrawRectWithText(screenshot,rect)

    cropped_image = screenshot[y:y+h, x:x+w]
    cv2.imwrite(path+serial+'-testscreenshot.png', cropped_image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

    cropped_image = screenshot[y+50:y+120, x+10:x+w-10]
    cv2.imwrite(path+serial+'-testscreenshot2.png', cropped_image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

def saveimg(d,rect):
    path='D:\\image3\\'

    device_info = d.device_info
    serial = device_info.get('serial')

    qqq(d,path,serial,rect)

    new_path=Picture_Synthesis(path+serial+'-testscreenshot2.png',serial)

    image=Image.open(new_path)

    target_width = 2*image.width
    target_height =2*image.height
    target_size = (target_width, target_height)
    upscaled_image = image.resize(target_size, 3)
    image_np = np.array(upscaled_image)
    gray_image = cv2.cvtColor(image_np, cv2.COLOR_BGR2BGRA)
    blurred_image = cv2.GaussianBlur(gray_image, (3, 3), 0)
    kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
    image_np = cv2.filter2D(blurred_image, -1, kernel)

    s = pytesseract.image_to_string(image_np, lang='chi_sim')

    text=s
    if text!=None:
        extracted_text = re.sub(r'[^\w\s]', '', text)
        extracted_text =extracted_text.rstrip("\n")
        if extracted_text != None:
            cleaned_text = extracted_text.replace(" ", "").replace('\n', '').replace('\r', '')
            directory = path
            if not os.path.exists(directory):
                os.makedirs(directory)

            source_file = path+serial+'-testscreenshot.png'
            target_directory = directory+'\\'

            os.makedirs(target_directory, exist_ok=True)

            files = os.listdir(directory)

            file_count = len(files)

            new_file_name = cleaned_text+str(file_count-1)+".png"

            shutil.copy(source_file, target_directory+new_file_name)

            return target_directory,new_file_name,cleaned_text

        else:
            print("未找到匹配的内容")
    else:
        print("未找到匹配的内容")

def compress_image(input_path, output_path, quality):
    original_size = os.path.getsize(input_path)
    image = Image.open(input_path)

    image.save(output_path, quality=quality)

    compressed_size = os.path.getsize(output_path)

def DrawRectWithText(screenshot, rect, text='aaa'):
    h, w = screenshot.shape[:2]

    x = int(w*rect[0])
    y = int(h*rect[1])
    width = int(w*rect[2])
    height = int(h*rect[3])
    return x,y,width,height

def getqd(d,arr,n=1):
    for i in range(n):
        for a in arr:
            screenshot = d.screenshot(format='opencv')
            img = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)
            template = cv2.imread('D:\\image\\'+a, 0)
            h,w=img.shape
            x,y=checkimg.match(w,img,template,0)
            if(x!=None):
                return x,y
        time.sleep(1)
    return None,None

def remove_suffix(text, suffix):
    if text.endswith(suffix):
        return text[:-len(suffix)]
    return text

def write_and_check_duplicate(filename, text):
    with open(filename, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    line_number = 0
    total=0
    for i, line in enumerate(lines):
        total+=1
        if text in line:
            line_number = i

    if line_number!=0:
        print(f"文件中已经存在相同内容，位于第 {line_number} 行。")
    else:
        line_number=total
        with open(filename, 'a', encoding='utf-8') as file:
            file.write(text)

    return line_number

def plot_text(path_to_your_image,imagename,name):

    path='D:\\image2\\'


    print('imagename=',imagename)

    image_pil = Image.open(path_to_your_image+imagename)
    image_np = np.array(image_pil)

    image = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)

    h,w, channels =image.shape

    suffix = ".png"

    result = remove_suffix(imagename, suffix)

    total_lines=0

    try:
        with open(path+'classes.txt', 'a', encoding='utf-8') as file:
            total_lines=write_and_check_duplicate(path+'classes.txt',name+'\n')
    except FileNotFoundError:
        with open(path+'classes.txt', 'w', encoding='utf-8') as file:
            total_lines=write_and_check_duplicate(path+'classes.txt',name+'\n')


    '''
    cv2.rectangle(image, top_left, bottom_right, (0, 255, 0), 2)

    cv2.imshow('Square', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    '''

def title(d,rect):
    path='D:\\image3\\'

    device_info = d.device_info
    serial = device_info.get('serial')

    qqq(d,path,serial,rect)

    new_path=Picture_Synthesis(path+serial+'-testscreenshot2.png',serial)

    image=Image.open(new_path)

    target_width = 2*image.width
    target_height =2*image.height
    target_size = (target_width, target_height)
    upscaled_image = image.resize(target_size, 3)
    image_np = np.array(upscaled_image)
    gray_image = cv2.cvtColor(image_np, cv2.COLOR_BGR2BGRA)
    blurred_image = cv2.GaussianBlur(gray_image, (3, 3), 0)
    kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
    image_np = cv2.filter2D(blurred_image, -1, kernel)

    s = pytesseract.image_to_string(image_np, lang='chi_sim')
    #print('string=',s)
    text=s
    if text!=None:
        extracted_text = re.sub(r'[^\w\s]', '', text)
        extracted_text =extracted_text.rstrip("\n")
        if extracted_text != None:
            cleaned_text = extracted_text.replace(" ", "").replace('\n', '').replace('\r', '')
            return cleaned_text

def jaccard_similarity(str1, str2):
    set1 = set(str1)
    set2 = set(str2)
    intersection = len(set1.intersection(set2))
    union = len(set1.union(set2))
    return intersection / union

def levenshtein_similarity(str1, str2):
    distance = Levenshtein.distance(str1, str2)
    return 1 - (distance / max(len(str1), len(str2)))

def imagecv(d):
    isyz=False
    if(True):
    #try:
        device_info = d.device_info
        serial = device_info.get('serial')

        #cv2.imshow("Cropped Image", cropped_image)
        #cv2.waitKey(0)
        #cv2.destroyAllWindows()
        screenshot = d.screenshot(format='opencv')
        names,im0,det=detect_image(screenshot, model, device='cpu',show=0)
        if(det is not None):
            print('det==',det.size())
        else:
            continue
        n=0;
        isleven=0;
        isClick=False;
        for *xyxy, conf, cls in det:
            x1, y1, x2, y2 = xyxy
            print(names[int(cls)], conf.item())
            label = '%s %.2f' % (names[int(cls)], conf)
            print("尺寸：", im0.shape)
            print("坐标：", (float(x1), float(y1), float(x2), float(y2)))
            print("标识：", label)
            x2=int((x1+x2)/2)
            y2=int((y1+y2)/2)
            if(conf.item()>0.6):
                return x2+random.randint(-5, 5), y2+random.randint(-5, 5),label

    '''
    except Exception as e:
        x,y=getqd(d,['imgres3.png','imgres.png','imgres2.png','imgres4.png'])
        if(x!=None):
            d.click(x,y)
            print('imgres x=',x,'y=',y)
        print("imagecv exception occurred:", e)
    '''
    return None,None,None


def get(device,code):
    start_time = time.time()

    d = u2.connect(device)
    #d.app_start('com.jym.gcmall')

    d.implicitly_wait(2)
    path='D:\\image\\'
    screenshotimg = path+device+'-screenshot.png'

    try:
        if(d(resourceId='com.android.browser:id/main_content').exists):
            print(device,code)
    except:
        print("except ............")
        print("adb -s "+device+ " shell /data/local/tmp/atx-agent server -d --stop")

        try:
            print(subprocess.Popen("adb -s "+device+ " shell /data/local/tmp/atx-agent server -d --stop").stdout.read())
        except subprocess.CalledProcessError as e:
            print("adb子进程执行出现异常:", e)
            return 'error'


    # 执行 ADB 命令
    output, error = d.shell("am start -a android.intent.action.VIEW -d 'https://accounts.qq.com'")
    print("Output:", output)
    print("Error:", error)

    time.sleep(2)

    m=0

    text=None

    while(True):
        screenshot = d.screenshot(format='opencv')
        x,y=getqd(d,['zhmm.png','zhmm2.png'],3)
        if(x!=None):
            print('x=',x,'y=',y)
            d.click(x,y)
            break
        else:
            time.sleep(1)
        if(m>5):
            d.shell("am force-stop com.android.browser")
            output, error = d.shell("am start -a android.intent.action.VIEW -d 'https://accounts.qq.com'")
            print("Output:", output)
            print("Error:", error)
            time.sleep(3)
        if(m>10):
            return 'error'
        m+=1

    #d.click(184.0 , 430.0)

    time.sleep(3)

    m=0
    while(True):
        #cv2.imwrite(path+device+'-test.png', screenshot, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

        x,y=getqd(d,['srqq.png','srqq2.png'],3)
        print(m,' srqq===','x=',x,'y=',y)
        if(x!=None):
            break
        else:
            time.sleep(1)
        if(m>10):
            return 'error'
        m+=1
        time.sleep(1)

    if(x!=None):
        d.click(x,y)
        d.send_keys(code)
        time.sleep(1)
        m=0
        while(True):
            x,y=getqd(d,['xyb.png','xyb2.png'],3)
            print(m,' srqq===','x=',x,'y=',y)
            if(x!=None):
                break
            else:
                time.sleep(1)
            if(m>10):
                return 'error'
            m+=1
            time.sleep(1)

        if(x!=None):
            d.click(x,y)

    time.sleep(2)

    isyz=imagecv(d,path,[0.02,0.12,0.96,0.5])
    #imagecv(d,path,[0.03,0.10,0.94,0.4])

    text='error'


    if(isyz):
            m=0
            while(True):
                time.sleep(2)
                x,y=getqd(d,['sjyz.png','sjyz2.png','sjyz3.png','sjyz4.png','sjyz5.png'])
                if(x!=None):
                    try:
                        #print('yzm2===',x,y)
                        screenshot = d.screenshot(format='opencv')
                        #text=checkimg.number(screenshot,[0.3,0.44,0.24,0.06])
                        text1=int(checkimg.number(screenshot,[0.3,0.45,0.1,0.05]))
                        text2=int(checkimg.number(screenshot,[0.473,0.45,0.05,0.05]))
                        text=str(text1)+","+str(text2)
                        #print('text=',text)
                    except Exception as e:
                        print('number except===',e)
                        text='无绑定'
                    finally:
                        break
                x,y=getqd(d,['srybdsjh.png'])
                if(x!=None):
                    try:
                        #print('yzm2===',x,y)
                        screenshot = d.screenshot(format='opencv')
                        #text=checkimg.number(screenshot,[0.3,0.44,0.24,0.06])
                        text1=int(checkimg.number(screenshot,[0.06,0.34,0.15,0.1]))
                        text2=int(checkimg.number(screenshot,[0.82,0.34,0.15,0.05]))
                        text=str(text1)+","+str(text2)
                        #print('text=',text)
                    except Exception as e:
                        print('number except===',e)
                        text='无绑定'
                    finally:
                        break
                else:
                    time.sleep(1)
                if(m>10):
                    return 'error'
                m+=1
                time.sleep(1)

    print('text=====',text)

